<template>
  <!-- 图件上传 -->
  <el-dialog v-model="openDialog" :title="dialogTitle" :before-close="handleClose" width="800px">
    <el-form ref="uploadRef" :model="form" :rules="rules" label-width="120px" v-loading="loading"
      style="margin-top:20px;">
      <el-row class="mt15">
        <el-col :span="24">
          <el-form-item label="图件名称" prop="mapName">
            <el-input style="width: 100%;" v-model="form.mapName" placeholder="请输入图件名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="图件分类" prop="mapClassify">
            <el-form-item label-width="0px" prop="mapLevel1Category">
              <el-select v-model="form.mapLevel1Category" placeholder="请选择一级图件分类" clearable disabled>
                <el-option v-for="item in chartClassifyOption" :key="item.dictId" :label="item.dictName"
                  :value="item.dictId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label-width="0px" prop="mapLevel2Category" style="margin-left: 60px;">
              <el-select v-model="form.mapLevel2Category" placeholder="请选择二级图件分类" clearable disabled>
                <el-option v-for="item in chartClassifyOption2" :key="item.dictItemId" :label="item.dictItemName"
                  :value="item.dictItemId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="mt15">
        <el-col :span="24">
          <el-form-item label="图件模板" prop="mapTemplateAttachId">
            <el-select v-model="form.mapTemplateAttachId" placeholder="请选择图件模板" clearable>
              <el-option v-for="item in mapTemplateList" :key="item.attachmentId" :label="item.mapTemplateName"
                :value="item.attachmentId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="mt15">
        <el-col :span="24">
          <el-form-item label="制图单位" prop="unit">
            <el-input style="width: 100%;" v-model="form.unit" placeholder="请输入制图单位" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="省" prop="provinceId">
            <el-select v-model="form.provinceId" placeholder="请输入省" @change="chooseFormProvince" style="width: 100%;">
              <el-option v-for="item in provinceFormData" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="市" prop="cityId">
            <el-select v-model="form.cityId" placeholder="请输入市" @change="chooseFormCity" style="width: 100%;"
              :disabled="cityDisabled">
              <el-option v-for="item in cityFormData" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="区/县" prop="areaId">
            <el-select v-model="form.areaId" placeholder="请输入区/县" @change="chooseFormArea" style="width: 100%;"
              :disabled="areaDisabled">
              <el-option v-for="item in areaFormData" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="图件描述" prop="mapDesc">
            <el-input v-model="form.mapDesc" type="textarea" maxlength="1000" show-word-limit
              :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入图件描述" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveSupergraph">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { printSupergraph } from "@/api/slideAssess/distributionPatternAnalysis/indexMap";
import { getDictByDictDirId, getDictItemsByDictId } from "@/api/resultManage/chartManger";
import { getPage } from '@/api/resultManage/templateModule.js';
import { getProvince, getChildArea } from "@/api/system/division";

const { proxy } = getCurrentInstance();
const props = defineProps(['open', 'taskId', 'geom', 'mapLevel1Category', 'mapLevel2Category', 'legendSetList', 'tempLayersSetList', 'printImgTitle']);
const emits = defineEmits(['closeImgDialog'])
const loading = ref(false);
const openDialog = ref(false);
const dialogTitle = ref("生成图件");
const chartClassifyOption = ref([]);//一级图件分类列表
const chartClassifyOption2 = ref([]);//二级图件分类列表
const mapTemplateList = ref([]);//图件模板列表
const provinceFormData = ref([]);//表单省
const cityFormData = ref([]);//表单市
const areaFormData = ref([]);//表单区、县

const handleClose = () => {
  openDialog.value = false;
  emits('closeImgDialog', true);
}
const validatorCity = (rule, value, callback) => {
  if (!value) {
    if (!form.value.province) {
      callback(new Error('请选择市'));
    } else if (form.value.province != '全国') {
      callback(new Error('请选择市'));
    } else {
      callback();
    }
  } else {
    callback();
  }
}
const validatorArea = (rule, value, callback) => {
  if (!value) {
    if (form.value.province == '全国') {
      callback();
    } else if ((form.value.city && form.value.city != '全部') || !form.value.city) {
      callback(new Error('请选择区/县'));
    } else {
      callback();
    }
  } else {
    callback();
  }
}
const data = reactive({
  form: {
    mapName: "",//图件名称
    mapLevel1Category: "",//一级图件分类
    mapLevel2Category: "",//二级图件分类
    provinceId: "",//省ID
    cityId: "",//市ID
    areaId: "",//区县ID
    mapDesc: "",//图件描述
    //临时使用
    mapTemplateAttachId: "",//图件模板文件ID
    unit: "",//制图单位
  },//图件信息
  legendVo: {
    unit: "",//制图单位
    dtId: "",//任务ID
    mapTemplate: {},//图件模板
    mapVO: {
      mapName: "",//图件名称
      mapLevel1Category: "",//一级图件分类
      mapLevel2Category: "",//二级图件分类
      provinceId: "",//省ID
      cityId: "",//市ID
      areaId: "",//区县ID
      mapDesc: "",//图件描述
    },//图件信息
    geomText: "",//图件显示区域空间数据
    legendSetList: [],//图层（临时图层）url列表--用于显示图例
    tempLayersSetList: [],//图层（临时图层）url列表--用于显示图层
    title:"",//图件标题
  },
  rules: {
    mapClassify: [{ required: true, trigger: "blur", validator: validatorMapClassify }],
    mapName: [{ required: true, message: "图件名称不能为空", trigger: "blur" }],
    mapDesc: [{ required: true, message: "图件描述不能为空", trigger: "blur" }],
    provinceId: [{ required: true, message: '请选择省', trigger: 'change' }],
    cityId: [{ trigger: 'change', validator: validatorCity }],
    areaId: [{ trigger: 'change', validator: validatorArea }],
    mapTemplateAttachId: [{ required: true, message: "图件模板不能为空", trigger: "blur" }],
    unit: [{ required: true, message: "制图单位不能为空", trigger: "blur" }],
  },
  queryParams: {
    mapLevel1Category: '',
    mapLevel2Category: '',
    mapTemplateName: '',
    page: 1,
    rows: 100
  },
})
const { form, legendVo, rules, queryParams } = toRefs(data);

//图片分类验证
function validatorMapClassify(rule, value, callback) {
  if (form.value.mapLevel1Category == '' || form.value.mapLevel1Category == undefined) {
    callback(new Error('图件分类不能为空'));
  } else if ((form.value.mapLevel1Category != '' || form.value.mapLevel1Category != undefined) && (form.value.mapLevel2Category == '' || form.value.mapLevel2Category == undefined)) {
    callback(new Error('二级图件分类不能为空'));
  } else if ((form.value.mapLevel1Category != '' || form.value.mapLevel1Category != undefined) && (form.value.mapLevel2Category != '' || form.value.mapLevel2Category != undefined)) {
    callback();
  }
}

//生成图件
function saveSupergraph() {
  proxy.$refs['uploadRef'].validate(valid => {
    if (valid) {
      save();
      function save() {
        legendVo.value.mapTemplateAttachId = form.value.mapTemplateAttachId;//图件模板文件ID
        legendVo.value.unit = form.value.unit;//制图单位
        legendVo.value.summaryText = '测试描述';
        legendVo.value.mapVO = form.value;//图件信息
        let bool = false;
        if (legendVo.value.geomText) {
          bool = true;
        } else if (legendVo.value.dtId) {
          bool = true;
        } else {
          bool = false;
          proxy.$modal.msgError("缺少图件范围");
          return;
        }
        //todo:应付测试，暂时注释下面两类判断
        legendVo.value.legendSetList=[];
        legendVo.value.tempLayersSetList=[];
        /*if (legendVo.value.legendSetList.length > 0) {
          bool = true;
        } else {
          bool = false;
          proxy.$modal.msgError("缺少图件图例列表！");
          return;
        }
        if (legendVo.value.tempLayersSetList.length > 0) {
          bool = true;
        } else {
          bool = false;
          proxy.$modal.msgError("缺少图件图层列表");
          return;
        }*/
        if(props.printImgTitle){//图件标题
          legendVo.value.title = props.printImgTitle;
        }
        if (bool) {
          loading.value = true;
          //生成图件
          printSupergraph(legendVo.value).then(response => {
            console.log(response);
            loading.value = false;
            proxy.$modal.msgSuccess("生成成功");
            openDialog.value = false;
          }).catch(() => {
            // proxy.$modal.msgError("生成失败");
            loading.value = false;
          });
        }
      }
    }
  });
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm("uploadRef");
  form.value.attachList = [];
}

//获取一级图件分类列表
function getChartClassifyList() {
  getDictByDictDirId().then(res => {
    chartClassifyOption.value = res.data;
  })
}

//获取二级图件分类列表
function getChartClassifyList2(value) {
  getDictItemsByDictId({ dictId: value }).then(res => {
    chartClassifyOption2.value = res.data;
    //获取图件模板列表
    getMapTemplateList();
  })
}

//获取图件模板列表
function getMapTemplateList() {
  getPage(queryParams.value).then(res => {
    const { code, data } = res
    if (code == 200) {
      mapTemplateList.value = data.rows ? data.rows : [];
    }
  })
}

const areaDisabled = ref(false)
const cityDisabled = ref(false)
/** 获取省列表 */
function getProvinceData() {
  getProvince().then(response => {
    provinceFormData.value = response.data;
    provinceFormData.value.unshift({ id: '全国', name: '全国', value: '全国' })
  });
}

function chooseFormProvince(value) {
  form.value.cityId = null;
  form.value.areaId = null;
  cityFormData.value = [];
  areaFormData.value = [];
  if (value == '全国') {
    cityDisabled.value = true
    areaDisabled.value = true
  } else {
    cityDisabled.value = false
    areaDisabled.value = false
    getChildArea(value).then(response => {
      cityFormData.value = response.data;
      cityFormData.value.unshift({ id: '全部', name: '全部', value: '全部' })
    });
  }
  form.value.province = provinceFormData.value.find(item => item.id == value)?.name;
}

function chooseFormCity(value) {
  form.value.area = null;
  areaFormData.value = [];
  if (value == '全部') {
    areaDisabled.value = true
  } else {
    areaDisabled.value = false
    getChildArea(value).then(response => {
      areaFormData.value = response.data;
      areaFormData.value.unshift({ id: '全部', name: '全部', value: '全部' })
    });
  }
  form.value.city = cityFormData.value.find(item => item.id == value)?.name
}

function chooseFormArea(value) {
  form.value.area = areaFormData.value.find(item => item.id == value)?.name;
}

//是否显示
const isOpen = watch(() => props.open, value => {// watch函数监听props.open
  openDialog.value = value;
}, { immediate: true });

//设置任务ID
watch(() => props.taskId, value => {// watch函数监听props.taskId
  legendVo.value.dtId = value;
}, { immediate: true });

//设置范围空间数据
watch(() => props.geom, value => {// watch函数监听props.geom
  legendVo.value.geomText = value;
  // legendVo.value.geomText = "MULTIPOLYGON(((73.48734500000006 15.701902308000058,73.48734500000006 53.56160200000005,135.08738700000004 53.56160200000005,135.08738700000004 15.701902308000058,73.48734500000006 15.701902308000058)))";
}, { immediate: true });

//设置一级图件分类
const setMapLevel1Category = watch(() => props.mapLevel1Category, value => {// watch函数监听props.mapLevel1Category
  form.value.mapLevel1Category = value;
  queryParams.value.mapLevel1Category = value;
  //获取二级图件分类列表
  getChartClassifyList2(form.value.mapLevel1Category);
}, { immediate: true });

//设置二级图件分类
const setMapLevel2Category = watch(() => props.mapLevel2Category, value => {// watch函数监听props.mapLevel2Category
  form.value.mapLevel2Category = value;
  queryParams.value.mapLevel2Category = value;
}, { immediate: true });

//设置图例（临时图层）url列表--用于显示图例
const setLegendSetList = watch(() => props.legendSetList, value => {// watch函数监听props.legendSetList
  legendVo.value.legendSetList = value;
  // legendVo.value.legendSetList = [{url:"http://10.13.155.192:8090/iserver/services/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg"}];
}, { immediate: true });

//设置图层（临时图层）url列表--用于显示图层
const setTempLayersSetList = watch(() => props.tempLayersSetList, value => {// watch函数监听props.tempLayersSetList
  legendVo.value.tempLayersSetList = value;
  // legendVo.value.tempLayersSetList = [{name:"中国",url:"http://10.13.155.192:8090/iserver/services/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg"}];
}, { immediate: true });

onMounted(() => {
  //获取一级图件分类列表
  getChartClassifyList();
  //获取省列表
  getProvinceData();
})
</script>

<style scoped lang="scss">
.new-dialogDiv {
  padding: 20px;
}

.expandTable {
  padding: 5px 20px 5px 205px;

  h3 {
    font-weight: bold;
  }

  p {
    margin: 0px;
    line-height: 25px !important;
  }
}

.tab-more {
  font-size: 16px;
  font-weight: bold;
  border-left: 3px solid #000000;
  font-family: PingFangSC-Medium;
  padding-left: 10px;
  margin-bottom: 20px;
}

.sub-tit {
  font-size: 14px;
  color: #707070;
  margin-bottom: 20px;
  margin-right: 10px;
  display: inline-block;
  font-weight: 600;
}

:deep(.el-drawer__header) {
  margin-bottom: 0px !important;
}

.el-form--inline .el-form-item {
  margin-right: 0px !important;
}

.spanStyle {
  display: inline-block;
  width: 40px;
  text-align: center;
}

:deep(.el-table__expand-icon) {
  display: none;
}
</style>